<template>
  <t-adaptive-page
    class="menu_mange"
    tableTitle="发货单列表"
    ref="TAdaptivePageDemo"
    isCopy
    :table="state.table"
    :columns="state.table.columns"
    :opts="opts"
    isExpansion
    columnSetting
    :isTTableSelfFilling="false"
    isShowWidthSize
    :widthSize="4"
    @size-change="handlesSizeChange"
    @page-change="handlesCurrentChange"
    @radio-change="selectionChange"
    @submit="conditionEnter"
  >
    <template #nickName="{ scope }">
      <div>{{ scope.row.nickName }}</div>
    </template>
    <template #ddate="{ scope }">
      <el-text type="primary">{{ parseTime(scope.row.ddate, '{y}-{m}-{d}') }}</el-text>
    </template>
    <template #footerBtn>
      <el-button type="danger" @click="addHandle()" v-if="checkPermission('新增', state.roleList)"
        >新增</el-button
      >
      <el-button type="primary" @click="TAdaptivePageDemo.TQueryConditionPage.checkHandle()"
        >查询</el-button
      >
      <el-button type="danger" @click="TAdaptivePageDemo.TQueryConditionPage.resetHandle()"
        >重置</el-button
      >
    </template>

    <template #ccode="{ scope }">
      <div>
        <el-link
            link
            @click="handerView(scope.row)"
            type="primary"
        >{{ scope.row.ccode }}</el-link>
      </div>
    </template>

    <template #IsBL="{ scope }">
      <div>
        {{ scope.row.IsBL ? '是' : '否'}}
      </div>
    </template>

    <template #toolbar>
      <div v-if="state.selectedRow">
        <el-button type="primary" @click="handerView(state.selectedRow)">详情</el-button>

        <el-button
            type="warning"

            @click="handleCheck(state.selectedRow)"
            :loading="loading"
            v-if="
            ['自由'].includes(state.selectedRow.StateID) &&
            state.selectedRow.confirm === '是' &&
            checkPermission('审核', state.roleList)
          "
        >审核</el-button
        >
        <el-button
            type="info"

            @click="handleUnCheck(state.selectedRow)"
            v-if="
            ['已审核'].includes(state.selectedRow.StateID) &&
            state.selectedRow.confirm === '是' &&
            checkPermission('弃审', state.roleList)
          "
        >弃审</el-button
        >
        <el-button
            type="primary"

            @click="handleCifmation(state.selectedRow, 1)"
            v-if="state.selectedRow.confirm !== '是' && checkPermission('发货确认', state.roleList)"
        >发货确认</el-button
        >
        <el-button
            type="primary"

            @click="handleCifmation(state.selectedRow, 0)"
            v-if="['自由'].includes(state.selectedRow.StateID) && state.selectedRow.confirm === '是' && checkPermission('撤销发货', state.roleList)"
        >撤销发货</el-button
        >


        <el-button type="primary" v-if="['自由'].includes(state.selectedRow.StateID) && checkPermission('删除', state.roleList)" @click="handleDelete(state.selectedRow)">
          删除
        </el-button>

<!--        <el-button type="primary" v-if="['自由'].includes(state.selectedRow.StateID) && checkPermission('编辑', state.roleList)" @click="handerEdit(state.selectedRow)">-->
<!--          编辑-->
<!--        </el-button>-->

        <el-button type="primary"  @click="handerEdit(state.selectedRow)">
          编辑
        </el-button>

        <el-button type="primary" v-if="checkPermission('快递信息', state.roleList)" @click="handleLogic(state.selectedRow,1)">
          快递信息
        </el-button>

        <el-button type="primary" v-if="
                  ['自由'].includes(state.selectedRow.StateID) &&
                  (['否'].includes(state.selectedRow.Iclose) || state.selectedRow.Iclose === null) &&
                  checkPermission('锁定', state.roleList)
                "
                   @click="handleLock(state.selectedRow,1)">
          锁定
        </el-button>

        <el-button type="primary" v-if="checkPermission('解锁', state.roleList)"
                   @click="handleLock(state.selectedRow,0)">
          解锁
        </el-button>

      </div>
      <div v-else style="color:red">
        选择数据后显示操作按钮
      </div>
    </template>


  </t-adaptive-page>
  <!--  新增 / 修改-->
  <el-dialog
      :title="state.addDialog.title"
      width="95%"
      v-model="state.addDialog.visible"
      v-if="state.addDialog.visible"
      draggable
      top="10px"
      :close-on-click-modal="false"
  >
    <div>
      <div class="dialog-footer" v-if="!state.addDialog.disabled">
        <el-button type="primary" @click="reference" >参照销售订单</el-button>
      </div>
      <el-form
          :model="state.addDialog.formData"
          :rules="state.addDialog.rules"
          ref="formRef"
          :disabled="state.addDialog.disabled"
      >
        <!--   第一行   -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="发货单单号" prop="ccode">
              <el-input
                  v-model="state.addDialog.formData.ccode"
                  placeholder="请输入发货单单号"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="单据日期" prop="ddate">
              <el-date-picker
                  v-model="state.addDialog.formData.ddate"
                  style="width: 100%"
                  format="YYYY-MM-DD "
                  value-format="YYYY-MM-DD"
                  type="datetime"
                  clearable
                  placeholder="选择日期"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="业务员" prop="salesman">
              <el-select
                  @change="changeSalesman"
                  v-model="state.addDialog.formData.salesman"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择业务员"
                  remote-show-suffix
              >
                <el-option
                    :label="item.cPsn_Name"
                    :value="item.cPsn_Num"
                    v-for="(item, index) in state.userList"
                    :key="index"
                >
                  <span style="float: left">{{ item.cPsn_Name }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                  >【{{ item.cDepName }}】</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="cDepName">
              <el-input
                  v-model="state.addDialog.formData.cDepName"
                  disabled
                  placeholder="请输入部门"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户" prop="cCusCode">
              <el-select
                  v-model="state.addDialog.formData.cCusCode"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请选择客户"
                  :remote-method="cnvbasdocMethod"
                  :loading="state.loading"
                  @change="changeCustCode"
                  remote-show-suffix
              >
                <el-option
                    v-for="item in cusoptions"
                    :key="item.cCusCode"
                    :label="item.ccusabbname"
                    :value="item.cCusCode"
                >
                  <span style="float: left">{{ item.ccusabbname }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                  >【{{ item.cCusCode }}】</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="税率" prop="taxrate">
              <el-input
                  v-model="state.addDialog.formData.taxrate"
                  type="number"
                  placeholder="请输入税率"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="物流公司" prop="logistics">
              <el-input
                  v-model="state.addDialog.formData.logistics"
                  placeholder="请输入物流公司"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="物流单号" prop="courierNumber">
              <el-input
                  v-model="state.addDialog.formData.courierNumber"
                  placeholder="请输入物流单号"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="物流金额" prop="number">
              <el-input
                  v-model="state.addDialog.formData.number"
                  placeholder="请输入物流金额"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="地址" prop="address">
              <el-input
                  v-model="state.addDialog.formData.address"
                  placeholder="请输入地址"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="是否发货确认" prop="confirm">
              <el-select
                  v-model="state.addDialog.formData.confirm"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择是否发货确认"
                  remote-show-suffix
              >
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售类型" prop="SalesType">
              <el-select
                  v-model="state.addDialog.formData.SalesType"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择合同类型"
                  remote-show-suffix
              >
                <el-option label="分期收款" value="分期收款"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户联系人" prop="contacts">
              <el-input
                  v-model="state.addDialog.formData.contacts"
                  placeholder="请输入客户联系人"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户联系人手机" prop="Telephone">
              <el-input
                  v-model="state.addDialog.formData.Telephone"
                  placeholder="请输入客户联系人手机"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="发货方式" prop="DeliveryMethod">
              <el-input
                  v-model="state.addDialog.formData.DeliveryMethod"
                  placeholder="请输入发货方式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="汇率" prop="ExchangeRate">
              <el-input
                  v-model="state.addDialog.formData.ExchangeRate"
                  type="number"
                  placeholder="请输入汇率"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种" prop="currency">
              <el-input
                  v-model="state.addDialog.formData.currency"
                  placeholder="请输入币种"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="单据状态" prop="StateID">
              <el-input
                  disabled
                  v-model="state.addDialog.formData.StateID"
                  placeholder="请输入单据状态"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否补录" prop="IsBL">

              <el-select
                  v-model="state.addDialog.formData.IsBL"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请选择是否补录"
                  remote-show-suffix
              >
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                  v-model="state.addDialog.formData.remarks"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left"></el-divider>
      </el-form>
      <el-row>
        <el-col :span="24">
          <div>
            <t-table
                title="明细"
                show-summary
                v-if="state.addDialog.visible"
                :table="state.table_d"
                :columns="state.table_d.columns"
                :summary-method="getSummaries"
                :isShowPagination="false"
                ref="singleEditTSelectTable"
                :listTypeInfo="state.listTypeInfo"
                @handleEvent="handleEvent"
                @validateError="validateError"
            >
              <!-- 自定义单元格编辑组件(多选下拉选择) -->
              <template #Warehouse="{ scope }">
                <el-select
                    v-model="scope.row[scope.column.property]"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="请选择仓库"
                    remote-show-suffix
                    :remote-method="remoteMethod"
                    :loading="state.loading"
                    @change="e => updateInv(e, scope.row)"
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in state.options"
                      :key="item.id"
                      :label="item.id"
                      :value="item.id"
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span
                        style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                    >
                        {{ item.id }}
                      </span>
                  </el-option>
                </el-select>
              </template>

              <!-- 自定义单元格编辑组件(多选下拉选择) -->
              <template #toolbar="{ scope }">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-select
                        filterable
                        :disabled="!isDetail"
                        remote
                        clearable
                        v-model="state.WarehouseHead"
                        reserve-keyword
                        placeholder="请选择仓库"
                        remote-show-suffix
                        :remote-method="remoteMethod"
                        :loading="state.loading"
                        @change="e => updateInvHead(e)"
                        style="width: 100%"
                    >
                      <el-option
                          v-for="item in state.options"
                          :key="item.id"
                          :label="item.id"
                          :value="item.id"
                      >
                        <span style="float: left">{{ item.name }}</span>
                        <span
                            style="
                              float: right;
                              color: var(--el-text-color-secondary);
                              font-size: 13px;
                            "
                        >
                            {{ item.id }}
                          </span>
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="12">
                    <el-date-picker
                        :disabled="!isDetail"
                        v-model="state.ddate"
                        style="width: 100%"
                        @change="e => updateInvHeadddtate(e)"
                        format="YYYY-MM-DD "
                        value-format="YYYY-MM-DD"
                        type="datetime"
                        clearable
                        placeholder="选择发货日期"
                    />
                  </el-col>
                </el-row>
              </template>
              <template #operatorT="{ scope }">
                <el-button
                    type="primary"
                    link
                    :disabled="!isDetail"
                    @click="editDel(scope.$index, scope)"
                >删除</el-button
                >
              </template>
            </t-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button
            type="primary"
            @click="submitForm"
            :loading="state.loading"
            v-if="!state.addDialog.disabled"
        >确 定</el-button
        >
      </div>
    </template>
  </el-dialog>
  <!--  变更-->
  <el-dialog
      title="物流信息"
      width="20%"
      v-model="state.update.visible"
      draggable
      :close-on-click-modal="false"
      @close="closeDialog"
  >
    <div>
      <el-form :model="state.update.formData" :rules="state.update.rules" ref="updateformRef">
        <!--   第一行   -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="物流公司" prop="logistics">
              <el-input
                  v-model="state.update.formData.logistics"
                  placeholder="请输入物流公司"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="物流单号" prop="courierNumber">
              <el-input
                  v-model="state.update.formData.courierNumber"
                  placeholder="请输入物流单号"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="物流金额" prop="number">
              <el-input
                  v-model="state.update.formData.number"
                  placeholder="请输入物流金额"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submituUpdateForm" :loading="state.loading"
        >确 定</el-button
        >
      </div>
    </template>
  </el-dialog>

  <el-dialog
      title="参照销售订单"
      width="100%"
      v-model="state.referenceLog.visible"
      draggable
      top="10px"
      :close-on-click-modal="false"
  >
    <referenceCom @changeTables="changeTables"></referenceCom>
  </el-dialog>
  <div class="ml5 mr5">
    <el-table
      show-summary
      :summary-method="getSummaries"
      :data="state.table_d.data"
      height="300px"
    >
      <el-table-column label="序号" type="index" width="55" align="center" show-overflow-tooltip />
      <el-table-column
        label="订单号"
        width="80"
        align="center"
        prop="SalesCode"
        show-overflow-tooltip
      />
      <el-table-column
        label="存货编码"
        width="120"
        align="center"
        prop="cInvCode"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="存货名称"
        width="200"
        align="center"
        prop="cInvName"
        show-overflow-tooltip
      />
      <el-table-column
        label="规格型号"
        width="120"
        align="center"
        prop="cInvStd"
        show-overflow-tooltip
      />
      <el-table-column
        label="发货数量"
        width="120"
        align="center"
        prop="quantity"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="库存数量"
        width="120"
        align="center"
        prop="kcs"
        show-overflow-tooltip
        sortable
      >
        <template #default="{ row }">
          <span v-if="row.kcs == undefined">加载中...</span>
          <span v-if="row.kcs - row.quantity < 0" style="color: red"
            >库存不足【{{ row.kcs }}】</span
          >
          <span v-else>{{ row.kcs }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="实际预发货日期"
        width="160"
        align="center"
        prop="deliverDate"
        show-overflow-tooltip
        sortable
      >
        <template #default="{ row }">
          <span>{{ parseTime(row.deliverDate, '{y}-{m}-{d}')  }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="仓库编码"
        width="120"
        align="center"
        prop="Warehouse"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="仓库名称"
        width="120"
        align="center"
        prop="cWhName"
        show-overflow-tooltip
      />
      <el-table-column
        label="客户存货编码"
        width="120"
        align="center"
        prop="cInvCodeK"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="客户存货规格型号"
        width="120"
        align="center"
        prop="cInvStdK"
        show-overflow-tooltip
      />
      <el-table-column
        label="含税单价"
        width="120"
        align="center"
        prop="iTaxUnitPrice"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="无税单价"
        width="120"
        align="center"
        prop="UnitPrice"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="税率"
        width="120"
        align="center"
        prop="taxRate"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        label="备注"
        width="120"
        align="center"
        prop="remarks"
        show-overflow-tooltip
      />
      <el-table-column
        label="合同号"
        width="120"
        align="center"
        prop="ContractNo"
        show-overflow-tooltip
      />
    </el-table>
  </div>
</template>

<script setup lang="tsx" name="selection">
import { computed, onMounted, reactive, ref, toRefs } from 'vue'
import { debounce, parseTime, dateDiff, checkPermission } from '@/utils/util'
import { cubasdocStore } from '@/stores/modules/cubasdoc'
import {
  getContractInfo,
  getContractList,
  findbaseBasicManage,
  findBoxData,
  getCode,
  GetInventory2,
  userRole
} from '@/api/base'
import {
  checkCode,
  salesOrderAdd,
  salesOrderList,
  ConfirmDelivery,
  CheckWareHouseList,
  salesOrderListDetails,
  ComboBoxWareHouseList,
  AddOrderlock,
  AddOrderUnlock,
  ConfirmDeliveryCX,
  ComboBoxDataList,
  salesOrderDelete,
  salesOrderCheck,
  salesOrderUnCheck,
  UpdateLogistics
} from '@/api/sale_deliver'
import { ElMessage, ElMessageBox } from 'element-plus'
import referenceCom from './components/reference.vue'

// 获取ref
const TAdaptivePageDemo: any = ref(null)
const handleDelete = async (row: any) => {

  ElMessageBox.confirm('此操作将删除该订单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let { code, news } = await salesOrderDelete({ ID: row.Sid })
    if (code === 1) {
      ElMessage.success(news)
      await getData()
    } else {
      ElMessage.error('删除失败，' + news)
    }
  })
}

const changeTables = async (row, chooseModel) => {
  state.addDialog.formData = {
    ...chooseModel,
    StateID: '自由',
    currency: '人民币',
    Sid: state.Sid,
    // ccode:state.ccode,
    ddate: parseTime(new Date(), '{y}-{m}-{d}'),
    Pdate: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
  }
  state.referenceLog.visible = false
  for (const item of row) {
    let invData = {
      Code: item.cInvCode
    }
    let { Data } = await GetInventory2(invData)

    if (Data && Data.length > 0 && Data[0].cDefWareHouse) {
      let invoptions = state.houseList.filter(its => {
        return its.id.toLowerCase().includes(Data[0].cDefWareHouse.toLowerCase())
      })[0]
      if (invoptions) {
        item.Warehouse = Data[0].cDefWareHouse
        item.cWhName = invoptions.name
      }
    }
    console.log(item.SalesCode,chooseModel.SalesCode)
    item.SalesCode = chooseModel.SalesCode
      item.SalesID = item.AutoID
      item.AID = null
      item.quantity = item.NotFHquantity
      state.table_d.data.push(item)
  }
}

const handleUnCheck = async (row: any) => {
  let { code, news } = await salesOrderUnCheck({ Sid: row.Sid })
  if (code == 1) {
    ElMessage.success('弃审成功')
    await getData()
  } else {
    ElMessage.error('弃审失败，' + news)
  }
}

const handleCifmation = async (row, type) => {
  let { code, news } =
    type === 1 ? await ConfirmDelivery({ id: row.Sid }) : await ConfirmDeliveryCX({ id: row.Sid })
  if (code == 1) {
    ElMessage.warning(news)
    await getData()
  } else {
    ElMessage.error(news)
  }
}
const handleLock = async (row, type) => {
  let { code, news } =
    type === 1 ? await AddOrderlock({ Sid: row.Sid }) : await AddOrderUnlock({ Sid: row.Sid })
  if (code == 1) {
    ElMessage.warning(news)
    await getData()
  } else {
    ElMessage.error(news)
  }
}

const handleLogic = async (row, type) => {
  state.update.formData = row
  state.update.visible = true
}

const handleCheck = async (row: any) => {
  try {
    loading.value = true
    let { code, news } = await salesOrderCheck({ Sid: row.Sid })
    if (code == 1) {
      ElMessage.success('审核成功')
      loading.value = false
      await getData()
    } else {
      ElMessage.error('审核失败，' + news)
    }
  } catch (e) {
    ElMessage.error('审核失败，' + e)
  } finally {
    loading.value = false
  }
}

// 选择复选框
const selectionChange = async (val: any) => {

  state.ids = val
  state.selectedRow = val

  let queryData = {
    table: 'SendAndReturnView',
    Sid: state.selectedRow.Sid
  }
  let axiosResponse = await salesOrderListDetails(queryData)

  const data = { Sid: state.selectedRow.Sid }
  let warehouseResponse =await CheckWareHouseList(data)

  let warehouseData = null;
  if (warehouseResponse && warehouseResponse.News=='200'){
    warehouseData = warehouseResponse.Data
  }

  if (axiosResponse.Rows.length > 0) {
    state.table_d.data = axiosResponse.Rows
    state.table_d.data.map(item => {
      if (warehouseData && warehouseData.length > 0) {
        item.kcs = warehouseData.reduce((total, row) => {
          return total + ((row.cInvCode === item.cInvCode) ? row.iQtty : 0)
        }, 0)
      } else {
        item.kcs = 0
      }
      return 0
    })
  }
}

const editDel = (index, row) => {
  state.table_d.data.splice(index, 1)
}

const handerView = async item => {

  //选择本条数据
  state.addDialog.formData = item
  state.addDialog.formData.cCusCode = item.cCusCodeID
  // state.ccode=item.ccode
  isDetail.value = false
  //查询详情赋值给表格
  let queryData = {
    table: 'SendAndReturnView',
    // selectvalue: 'undefined',
    // value: 'undefined',
    // WF: '',
    Sid: item.Sid
  }
  let axiosResponse = await salesOrderListDetails(queryData)

  if (axiosResponse.Rows.length > 0) {
    state.table_d.data = axiosResponse.Rows
    //state.addDialog.formData.ContractNo = axiosResponse.Rows[0].ContractNo
  }
  state.addDialog.disabled = true
  state.addDialog.visible = true
  state.addDialog.title = '详情'
}

const handerEdit = async item => {

  //选择本条数据
  state.addDialog.formData = item
  state.addDialog.formData.cCusCode = item.cCusCodeID
  state.Sid=item.Sid
  isDetail.value = true
  //查询详情赋值给表格
  let queryData = {
    table: 'SendAndReturnView',
    // selectvalue: 'undefined',
    // value: 'undefined',
    // WF: '',
    Sid: item.Sid
  }
  let axiosResponse = await salesOrderListDetails(queryData)

  if (axiosResponse.Rows.length > 0) {
    state.table_d.data = axiosResponse.Rows
    //state.addDialog.formData.ContractNo = axiosResponse.Rows[0].ContractNo
  }
  state.addDialog.disabled = false
  state.addDialog.visible = true
}

// 取消选中
const cancelSelect = () => {

  if (state.ids.length > 0) {

    // 方式一
    TAdaptivePageDemo.value.clearSelection()
    // 方式二（TTablePage ref）
    // TAdaptivePageDemo.value.TTablePage.clearSelection()
  }
}
const isDetail = ref(false)
const loading = ref(false)
const state: any = reactive({
  ids: [],
  Sid: null,
  selectedRow:null,
  roleList: [],
  ccode: null,
  WarehouseHead: '',
  ddate: '',
  invOptions: [],
  queryData: {
    depcode: '08'
  },
  table: {
    border: true,
    firstColumn: { type: 'radio', fixed: true },
    currentPage: 1,
    pageSize: 10,
    total: 0,
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      // { prop: 'Sid', label: '数据标识', width: 100},
      { prop: 'ccode', label: '发货单号', width: 150,fixed: 'left',slotName: 'ccode', },
      { prop: 'ddate', label: '单据日期', slotName: 'ddate', width: 110 },
      { prop: 'remarksT', label: '表头备注', showOverflowTooltip: true, width: 120 },
      { prop: 'StateID', label: '单据状态', width: 100 },
      { prop: 'ReviewedBy', label: '审核人', width: 100 },
      { prop: 'AuditTime', label: '审核时间', width: 130 },
      { prop: 'cCusCodeID', label: '客户编码', width: 100 },
      { prop: 'cCusName', label: '客户名称', width: 140 },
      { prop: 'confirm', label: '是否发货确认', width: 110 },

      { prop: 'Preparer', label: '制单人', width: 100 },
      { prop: 'Pdate', label: '制单时间', width: 100 },
      { prop: 'DeliveryMethod', label: '发货方式', width: 100 },
      { prop: 'IsBL', label: '是否补录', width: 100,slotName: 'IsBL' },
      // { prop: 'Telephone', label: '联系电话', width: 100 },
      // { prop: 'address', label: '客户地址', width: 130 },
      { prop: 'number', label: '物流金额', width: 90 },
      { prop: 'logistics', label: '物流公司', width: 100 },
      { prop: 'courierNumber', label: '快递单号', width: 100 },
      { prop: 'cDepName', label: '部门', width: 100 },
      { prop: 'depcode', label: '部门编码', width: 100 },
      { prop: 'cPsn_Name', label: '业务员', width: 90 },

      // { prop: 'ExchangeRate', label: '汇率', width: 80 },
      // { prop: 'currency', label: '币种', width: 100 },
      { prop: 'SalesType', label: '销售类型', width: 100 },

      { prop: 'Iclose', label: '锁定状态', width: 100 },

      { prop: 'Modified', label: '修改人', width: 100 },
      { prop: 'Mdate', label: '修改时间', width: 100 },
    ]
  },
  addDialog: {
    title: '新增',
    visible: false,
    loading: false,
    disabled: false,
    formData: {
      ddate: parseTime(new Date(), '{y}-{m}-{d}'),
      // BodyJson:[],
      taxrate: 13,
      repair: '否',
      SalesType: '分期付款',
      TranType: '分期付款',
      salesman: '',
      cDepName: '',
      depcode: '',
      contacts: '',
      Telephone: '',
      DeliveryMethod: '快递',
      PackingMethod: '',
      remarks: '',
      ExchangeRate: '1',
      Pdate: parseTime(new Date(), '{y}/{m}/{d} {h}:{i}:{s}'),
      Preparer: '',
      change: '',
      StateID: '自由'
    },
    rules: {
      ccode: [
        { required: true, message: '请输入单号', trigger: 'blur' },
        //请求接口校验是否重复
        {
          validator: async (rule, value, callback) => {
            try {
              let res = await checkCode({ FHNum:value})

              if (res.Code!=='OK') {
                callback(new Error('单号已存在'))
              } else {
                callback()
              }
            } catch (e) {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      cCusCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
      ContractNo: [{ required: true, message: '请选择合同号', trigger: 'blur' }],
      repair: [{ required: true, message: '请选择是否补录', trigger: 'change' }],
      SalesType: [{ required: true, message: '请选择销售类型', trigger: 'change' }],
      // SalesCode: [{ required: true, message: "请输入销售订单号", trigger: "blur" }],
      TranType: [{ required: true, message: '请选择交易类型', trigger: 'change' }],
      ddate: [{ required: true, message: '请选择单据时间', trigger: 'change' }],
      salesman: [{ required: true, message: '请选择业务员', trigger: 'change' }],

      taxrate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
      ExchangeRate: [{ required: true, message: '请输入汇率', trigger: 'blur' }],
      IsBL: [{ required: true, message: '请选择是否补录', trigger: 'blur' }]
    }
  },
  table_d: {
    rules: {},
    data: [],
    columns: [
      {
        prop: 'rowno',
        label: '序号'
      },
      {
        prop: 'SalesCode',
        label: '订单号',
        minWidth: '140'
      },
      {
        prop: 'cInvCode',
        label: '存货编码',
        minWidth: '120'
      },
      {
        prop: 'cInvName',
        label: '存货名称',
        minWidth: '200'
      },
      {
        prop: 'cInvStd',
        label: '规格型号',
        minWidth: '120'
      },
      {
        prop: 'quantity',
        label: '发货数量',
        minWidth: '180',
        canEdit: isDetail,
        headerRequired: true,
        configEdit: {
          label: '发货数量',
          type: 'inputNumber',
          bind: { min: 1 },
          rules: { required: true, message: '请输入发货数量', trigger: 'blur' },
          editComponent: 'el-input-number',
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: 'deliverDate',
        minWidth: '160',
        label: '实际预发货日期',
        canEdit: isDetail,
        headerRequired: true,
        configEdit: {
          label: '实际预发货日期',
          type: 'date',
          rules: { required: true, message: '请选择实际预发货日期', trigger: 'blur' },
          editComponent: 'el-date-picker'
          // bind: { valueFormat: "yyyy-mm-dd" }
        }
      },

      {
        prop: 'Warehouse',
        label: '仓库编码',
        minWidth: '180',
        canEdit: isDetail,
        configEdit: {
          label: '仓库',
          type: 'inputNumber',
          editSlotName: 'Warehouse'
        }
      },
      {
        prop: 'cWhName',
        label: '仓库名称',
        minWidth: '180'
      },

      {
        prop: 'cInvNameK',
        minWidth: '120',
        label: '客户存货名称',
        headerRequired: true,
        canEdit: isDetail,
        configEdit: {
          label: '客户存货名称',
          type: 'input',
          rules: { required: true, message: '请输入客户存货名称', trigger: 'blur' },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'cInvStdK',
        minWidth: '160',
        label: '客户存货规格型号',
        canEdit: isDetail,
        configEdit: {
          label: '客户存货规格型号',
          type: 'input',
          editComponent: 'el-input'
        }
      },
      {
        prop: 'iTaxUnitPrice',
        label: '含税单价',
        minWidth: '180',
        headerRequired: true,
        canEdit: false,
        configEdit: {
          label: '单价',
          type: 'inputNumber',
          bind: { min: 0 },
          editComponent: 'el-input-number',
          rules: { required: true, message: '请输入单价', trigger: 'blur' },
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: 'UnitPrice',
        label: '无税单价',
        minWidth: '180',
        headerRequired: true,
        canEdit: false,
        configEdit: {
          label: '单价',
          type: 'inputNumber',
          bind: { min: 0 },
          editComponent: 'el-input-number',
          rules: { required: true, message: '请输入单价', trigger: 'blur' },
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },

      {
        prop: 'taxRate',
        label: '税率',
        minWidth: '180',
        headerRequired: true,
        canEdit: isDetail,
        configEdit: {
          label: '税率',
          type: 'inputNumber',
          bind: { min: 0 },
          rules: { required: true, message: '请输入税率', trigger: 'blur' },
          editComponent: 'el-input-number',
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },

      {
        prop: 'remarks',
        minWidth: '160',
        label: '备注',
        canEdit: isDetail,
        configEdit: {
          label: '备注',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入备注", trigger: "blur" },
          editComponent: 'el-input'
        }
      },

      {
        prop: 'ContractNo',
        minWidth: '160',
        label: '合同号',
        canEdit: isDetail,
        configEdit: {
          label: '合同号',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: '请输入合同号', trigger: 'blur' },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'operatorT',
        label: '操作',
        minWidth: '180',
        fixed: 'right',
        canEdit: true,
        configEdit: {
          editSlotName: 'operatorT'
        }
      }
    ]
  },
  userList: [],
  invList: [],
  update: {
    formData: {
      StateID: '自由'
    },
    visble: false,
    rules: {
      logistics: [{ required: true, message: '请输入物流公司', trigger: 'blur' }],
      courierNumber: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
    }
  },
  table_u: {
    rules: {},
    firstColumn: { type: 'index', label: '序号', props: 'LineNum' }, // 显示序列号
    data: [],
    columns: [
      {
        prop: 'rowno',
        label: '序号'
      },
      {
        prop: 'ChangeContent',
        label: '变更内容',
        minWidth: '120'
      },
      {
        prop: 'quantity',
        label: '数量',
        minWidth: '180',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '数量',
          type: 'inputNumber',
          bind: { min: 0 },
          rules: { required: true, message: '请输入数量', trigger: 'blur' },
          editComponent: 'el-input-number',
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          }
        }
      },
      {
        prop: 'Yquantity',
        label: '原数量',
        minWidth: '180'
      },
      {
        prop: 'Xingguan',
        label: '是否行关闭',
        minWidth: '180',
        slotName: 'Xingguan',
        configEdit: {
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          }
        }
      },
      {
        prop: 'CustomerOrder',
        minWidth: '160',
        label: '客户订单号',
        // headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '客户订单号',
          type: 'input',
          bind: { min: 0 },
          // rules: { required: true, message: "请输入客户订单号", trigger: "blur" },
          editComponent: 'el-input',
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          }
        }
      },
      {
        prop: 'deliverDate',
        minWidth: '160',
        label: '实际预发货日期',
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: '实际预发货日期',
          type: 'date',
          rules: { required: true, message: '请选择实际预发货日期', trigger: 'blur' },
          editComponent: 'el-date-picker',
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          }
          // bind: { valueFormat: "yyyy-mm-dd" }
        }
      },

      {
        prop: 'YdeliverDate',
        minWidth: '160',
        label: '原实际预发货日期'
      },
      {
        prop: 'DateChange',
        minWidth: '160',
        label: '发货日期变化'
      },

      {
        prop: 'cInvCode',
        label: '存货编码',
        placeholder: '请选择存货',
        minWidth: '120'
      },
      {
        prop: 'cInvName',
        label: '存货名称',
        minWidth: '200'
      },
      {
        prop: 'cInvStd',
        minWidth: '120',
        label: '规格型号'
      },

      {
        prop: 'cInvCodeK',
        minWidth: '120',
        label: '客户存货编码'
      },

      {
        prop: 'cInvNameK',
        minWidth: '120',
        label: '客户存货名称'
      },
      {
        prop: 'cInvStdK',
        minWidth: '160',
        label: '客户存货规格型号'
      },
      {
        prop: 'completeDate',
        minWidth: '160',
        label: '预完工日期',
        canEdit: true,
        // headerRequired: true,
        configEdit: {
          label: '预完工日期',
          type: 'date',
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          },
          //rules: { required: true, message: "请选择预生产完工日期", trigger: "change" },
          editComponent: 'el-date-picker'
          // bind: { valueFormat: 'yyyy-mm-dd' }
        }
      },
      {
        prop: 'YcompleteDate',
        minWidth: '160',
        label: '原预完工日期'
      },
      {
        prop: 'remarks',
        minWidth: '160',
        label: '备注',
        canEdit: true,
        configEdit: {
          label: '备注',
          type: 'input',
          bind: { min: 0 },
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          },
          // rules: { required: true, message: "请输入备注", trigger: "blur" },
          editComponent: 'el-input'
        }
      },
      {
        prop: 'UnitPrice',
        label: '单价',
        minWidth: '180',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '单价',
          type: 'inputNumber',
          bind: { min: 0 },
          editComponent: 'el-input-number',
          rules: { required: true, message: '请输入单价', trigger: 'blur' },
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          }
        }
      },

      {
        prop: 'taxRate',
        label: '税率',
        minWidth: '180',
        headerRequired: true,
        canEdit: true,
        configEdit: {
          label: '税率',
          type: 'inputNumber',
          bind: { min: 0 },
          rules: { required: true, message: '请输入税率', trigger: 'blur' },
          editComponent: 'el-input-number',
          eventHandle: {
            change: ({ val, prop, scope }) => updateChangeContent(val, prop, scope)
          }
        }
      }
    ]
  },
  referenceLog: {
    visible: false
  },
  houseList: []
})

const opts = computed(() => {
  return {
    SalesCode: {
      label: '销售订单号',
      comp: 'el-input'
    },
    ccode: {
      label: '发货单号',
      comp: 'el-input'
    },
    // depcode: {
    //   label: '部门',
    //   placeholder: '请选择部门',
    //   comp: 't-select',
    //   isSelfCom: true,
    //   bind: {
    //     valueCustom: 'cDepCodeid',
    //     labelCustom: 'cDepCodename',
    //     optionSource: cubasdoc.depts
    //   }
    // },
    // cInvCode: {
    //   label: '存货信息',
    //   placeholder: '请选择存货',
    //   comp: 't-select',
    //   isSelfCom: true,
    //   bind: {
    //     valueCustom: 'id',
    //     labelCustom: 'name',
    //     optionSource: state.invOptions
    //   }
    // },
    cCusCode: {
      label: '客户',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'cCusCode',
        labelCustom: 'ccusname',
        optionSource: cubasdoc.data
      }
    },
    StateID: {
      label: '单据状态',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'value',
        labelCustom: 'label',
        optionSource: [
          {
            label: '已审核',
            value: '已审核'
          },
          {
            label: '自由',
            value: '自由'
          },
          {
            label: '锁定',
            value: '锁定'
          }
        ]
      }
    },
    confirm: {
      label: '是否发货确认',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'value',
        labelCustom: 'label',
        optionSource: [
          {
            label: '是',
            value: '是'
          },
          {
            label: '否',
            value: '否'
          }
        ]
      }
    },

    salesman: {
      label: '业务员',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'cPsn_Num',
        labelCustom: 'cPsn_Name',
        optionSource: state.userList
      }
    },
    dbdate: {
      label: '制单时间',
      comp: 'el-date-picker',
      span: 1,
      event: 'date',
      bind: {
        rangeSeparator: '-',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD',
        type: 'daterange'
      }
    },
    AuditTime: {
      label: '审核时间',
      comp: 'el-date-picker',
      span: 1,
      bind: {
        valueFormat: 'YYYY-MM-DD'
      }
    },
    remarksT: {
      label: '备注',
      comp: 'el-input'
    },
    contacts: {
      label: '客户联系人',
      comp: 'el-input'
    }
  }
})
// 最终参数获取
const getQueryData = computed(() => {
  let queryList = []
  state.queryData.depcode = '08'
  const res = toRefs(state.queryData)
  Object.keys(res).forEach(item => {

    let data = {}
    if (res[item].value) {
      if (item === 'dbdate') {
        data = {
          field: 'Pdate',
          op: 'and',
          value: res[item].value[0],
          type: 'date'
        }
        queryList.push(data)
        data = {
          field: 'Pdateend',
          op: 'and',
          value: res[item].value[1],
          type: 'date'
        }
        queryList.push(data)
      } else if (item === 'AuditTime') {
        data = {
          field: 'AuditTime',
          op: 'and',
          value: res[item].value,
          type: 'date'
        }
        queryList.push(data)
      } else {
        data = {
          field: item,
          op: 'and',
          value: res[item].value,
          type: 'text'
        }
        queryList.push(data)
      }
    }
  })
  return queryList.length > 0 ? { rules: queryList, op: 'and' } : null
})
// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data
  state.table.currentPage =1
  state.table.pageSize = 10
  getData()
}
onMounted(() => {
  getUserList()
  getInvList()
  getHouseList()
  findContracts()
  getData()
  initRoleList()
})
//获取仓库
const getHouseList = async () => {
  const Rows = await ComboBoxWareHouseList()
  state.houseList = Rows
}

// 获取菜单数据
const getData = async () => {

  let queryData = {
    table: 'SendAndReturnView',
    name: 'undefined',
    value: 'undefined',
    DoType: 0,
    KJTJ: ''
  }
  if (getQueryData.value) {
    queryData.KJTJ = JSON.stringify(getQueryData.value)
  }
  const formData = new FormData()
  formData.append('page', state.table.currentPage) // 添加字段
  formData.append('pagesize', state.table.pageSize) // 添加另一个字段

  const { Rows, Total } = await salesOrderList(queryData, formData)
  state.table.data = Rows
  state.table.total = Total
  state.selectedRow = null
}
// 页面大小
const handlesSizeChange = (val: any) => {
  state.table.pageSize = val
  getData()
}
// 页码
const handlesCurrentChange = (val: any) => {
  state.table.currentPage = val
  getData()
}

//校验表单需要定义ref
let formRef = ref({})
//打开新增窗口
async function addHandle() {
  let map = {
    code: 'HTFH'
  }
  let res = await getCode(map)
  // state.ccode = res.Data
  state.addDialog.formData = {}
  state.addDialog.disabled = false
  state.addDialog.visible = true
  isDetail.value = true
  state.Sid = null
  state.table_d.data = []
}
//关闭弹窗
function closeDialog() {
  state.addDialog.visible = false
  state.update.visible = false
  // formRef.value?.resetFields()
  state.table_d.data = []
  state.Sid = null
  getData()
}
function reference() {
  state.referenceLog.visible = true
}

const singleEditTSelectTable: any = ref(null)
//提交数据
const submitForm = debounce(
  async () => {
    state.loading = true
    state.selectedRow=null
    // state.addDialog.formData.Sid=null
    state.addDialog.formData.Iclose = '否'
    formRef.value.validate(async vaild => {
      if (vaild) {
        singleEditTSelectTable.value.saveMethod(async data => {

          // 提交表单
          let subData = {
            HeaderJson: [state.addDialog.formData],
            BodyJson: data
          }

          const res = await salesOrderAdd({ list: subData })
          if (res.code === 1) {
            ElMessage.success(res.news)
            closeDialog()
            await getData()
          } else {
            ElMessage.error(res.news)
          }
        })
        state.loading = false
        state.Sid = null
      }
      state.loading = false
    })
  },
  false,
  1000
)

let updateformRef = ref({})
const singleUpdateTSelectTable: any = ref(null)
const submituUpdateForm = debounce(
  async () => {
    state.loading = true

    state.addDialog.formData.ddate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    state.addDialog.formData.Pdate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    updateformRef.value.validate(async vaild => {
      if (vaild) {
        // 提交表单
        let subData = {
          Sid: state.update.formData.Sid,
          logistics: state.update.formData.logistics,
          courierNumber: state.update.formData.courierNumber,
          number: state.update.formData.number
        }
        const res = await UpdateLogistics(subData)
        if (res.code === 1) {
          ElMessage.success(res.news)
          closeDialog()
          await getData()
        } else {
          ElMessage.error(res.news)
        }
        state.loading = false
      }
      state.loading = false
    })
  },
  false,
  1000
)

//客户选择
function changeCustCode(e) {
  //过滤客户
  let cusoptions = cubasdoc.data.filter(its => {
    return its.cCusCode.toLowerCase().includes(e.toLowerCase())
  })[0]

  if (cusoptions) {
    //赋值
    state.addDialog.formData.address = cusoptions.ccusAddress
  }
}

const cubasdoc = cubasdocStore()
//选择项
const cusoptions = ref(cubasdoc.data)
const cnvbasdocMethod = query => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter(its => {
        return (
          its.cCusCode.toLowerCase().includes(query.toLowerCase()) ||
          its.ccusabbname.toLowerCase().includes(query.toLowerCase())
        )
      })
    }, 200)
  } else {
    cusoptions.value = cubasdoc.data
  }
}

// 编辑单元格监听事件
const handleEvent = (type, val, index) => {

}

// 错误校验提示
const validateError = list => {
  list.map(val => {
    setTimeout(() => {
      ElMessage.error(`${val}是必填项！`)
    }, 100)
  })
}

function addOneTable() {
  state.table_d.data.push({
    //获取最大行号加1
    // LineNum: state.table.data.length + 1,
  })
}

//查询存货 -- 增加防抖函数
const remoteMethod = debounce(
  async query => {
    if (query) {
      state.loading = true
      state.loading = false

      //state.invList = Data
      state.options = state.houseList.filter(item => {
        return (
          item.name.toLowerCase().includes(query.toLowerCase()) ||
          item.id.toLowerCase().includes(query.toLowerCase())
        )
      })
    } else {
      state.options = state.houseList
    }
  },
  200,
  false
)

//存货选择
async function updateInvHead(e) {

  //过滤客户
  let invoptions = state.houseList.filter(its => {
    return its.id.toLowerCase().includes(e.toLowerCase())
  })[0]
  if (invoptions) {
    //赋值
    state.table_d.data.forEach(item => {
      item.cWhName = invoptions.name
      item.Warehouse = invoptions.id
    })
  }
}

async function updateInvHeadddtate(e) {
  state.table_d.data.forEach(item => {
    item.deliverDate = e
  })
}

//存货选择
async function updateInv(e, row) {

  if (e) {
    //过滤客户
    let invoptions = state.houseList.filter(its => {
      return its.id.toLowerCase().includes(e.toLowerCase())
    })[0]
    if (invoptions) {
      //赋值
      row.cWhName = invoptions.name
    }
  } else {
    row.cWhName = ''
  }
}

//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
      'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}

function changeSalesman(e) {
  //过滤客户
  let useroptions = state.userList.filter(its =>
    its.cPsn_Num.toLowerCase().includes(e.toLowerCase())
  )
  if (useroptions) {
    //赋值
    state.addDialog.formData.cDepName = useroptions[0].cDepName
    state.addDialog.formData.depcode = useroptions[0].cDept_num
  }
}

//查询存货信息
const getInvList = async () => {
  let Rows = await findBoxData()
  state.invList = Rows


  state.invOptions = await ComboBoxDataList()
}

// 数量change事件
const numChange = (val, prop, scope) => {

  let rate = state.table_d.data[scope.$index].taxRate / 100 + 1
  //计算含税单价和无税单价
  state.table_d.data[scope.$index].iTaxUnitPrice = (
    Number(state.table_d.data[scope.$index].UnitPrice || 0) * rate
  ).toFixed(2)

  state.table_d.data[scope.$index].UnitPrice = (
    Number(state.table_d.data[scope.$index].iTaxUnitPrice || 0) / rate
  ).toFixed(5)
}

const updateChangeContent = (val, prop, scope) => {

  //将变更字段加入到ChangeContent，形成逗号字符串
  let split = state.table_u.data[scope.$index].ChangeContent?.split(',')
  if (!split.includes(scope.column.label)) {
    state.table_u.data[scope.$index].ChangeContent =
      state.table_u.data[scope.$index].ChangeContent + scope.column.label + ','
  }
  //计算变更字段
  //发货日期变化
  if (prop === 'deliverDate') {
    //计算YDeliveryDate 与 DeliveryDate 时间相差天数
    let s = parseTime(val, '{y}-{m}-{d}')


    let number = dateDiff(
      parseTime(val, '{y}-{m}-{d}'),
      parseTime(state.table_u.data[scope.$index].YdeliverDate, '{y}-{m}-{d}')
    )
    let days = Math.abs(number) //取绝对值
    if (number > 0) {
      state.table_u.data[scope.$index].DateChange = '提前' + days + '天'
    } else {
      state.table_u.data[scope.$index].DateChange = '延后' + days + '天'
    }

  }
}

function updateContarctInfo(e) {
  //查询过滤合同信息
  let contractInfo = cubasdoc.contractList.find(item => item.ContractNum === e)
  if (contractInfo) {
    //赋值
    state.addDialog.formData.cCusCode = contractInfo?.CustCode
    state.addDialog.formData.address = contractInfo?.CustAdd
    state.addDialog.formData.cCusName = contractInfo?.CustName

    state.addDialog.formData.taxrate = contractInfo?.Rate

    //调用查询合同详细信息
    findContractInfo(contractInfo.Id)
  }
}

//查询合同详细信息
async function findContractInfo(id) {
  let { Data } = await getContractInfo({ id: id })
  if (Data?.SubList2) {
    //赋值合同明细
    state.table_d.data = Data.SubList2.map(item => {
      return {
        cInvName: item.CinvName,
        cInvCode: item.CinvCode,
        cInvStd: item.CinvAdd,

        quantity: item.Quantity,
        UnitPrice: item.Price,
        ContractID: item.Id,
        ContractNo: Data.Main.ContractNum,
        taxRate: Data.Main.Rate,
        // deliver:parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
        //deliverDate:"2024-08-15T16:00:00.000Z",
        // MaterialShutdown:"1753-01-01 00:00:00",
        // DeliveryTime:"1753-01-01 00:00:00",
        upgrade: '是'
      }
    })

  }
}

//查询合同信息
async function findContracts() {
  let queryData = {
    ContractType: null,
    CustCode: null,
    CustName: null,
    ContractNum: null,
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null
  }
  //获取合同信息
  let contractData = await getContractList(queryData)
  cubasdoc.setContractList(contractData.Data)
}
const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if ([1, 2, 3, 4,7, 8, 9, 10,13, 14, 15, 16, 17, 26].includes(index)) {
      sums[index] = 'N/A'
      return
    }

    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] += ''
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合同销售发货通知单' })
  state.roleList = res.items
}
</script>
<style lang="scss" scoped>
.t_adaptive_page {
  height: 80%;
}
.t_adaptive_page .right_content .t_table_self-filling .t-table .el-table {
  height: 40vh;
}
</style>
